package tech.aistar.day02;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 本类用来演示:
 *
 * @author: success
 * @date: 2021/4/16 10:00 上午
 */
@WebServlet(urlPatterns = "/day02/session/*")
public class SessionDemo extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String pathInfo = req.getPathInfo();
        switch (pathInfo){
            case "/set":
                HttpSession session = req.getSession();
                //将数据放入到session作用域
                //接受参数localhost:8888/aistar/day02/session/set?name=tom
                String name = req.getParameter("name");
                session.setAttribute("name",name);

                //session.removeAttribute("name");
                //session.invalidate();

                resp.sendRedirect("/aistar/day02/session/get");
                break;
            case "/get":
                //从session中获取数据
                PrintWriter out = resp.getWriter();
                HttpSession ses = req.getSession();
                String age = (String) ses.getAttribute("name");
                out.println(age);
                break;
        }
    }
}
